package com.yonyou.pmclouds.basecom.lock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class PMLock {
    public static final long DEFAULT_TIME_OUT = 300000;
    public static final long DEFAULT_TIME_LOCK_TO_WAIT = 0;

    private static RedissonClient redissonClient;

    @Autowired
    public PMLock(RedissonClient client) {
        redissonClient = client;
    }

    public static Boolean addLock(String key) {
        RLock lock = redissonClient.getLock(key);
        return lock.tryLock();
    }

    public static Boolean addLock(String key, long timeout) throws InterruptedException {
        RLock lock = redissonClient.getLock(key);
        return lock.tryLock(DEFAULT_TIME_LOCK_TO_WAIT, timeout, TimeUnit.MILLISECONDS);
    }

    public static Boolean addLock(String key, long waittime, long timeout) throws InterruptedException {
        RLock lock = redissonClient.getLock(key);
        return lock.tryLock(waittime, timeout, TimeUnit.MILLISECONDS);
    }

    public static void releaseLock(String key) {
        RLock lock = redissonClient.getLock(key);
        lock.unlock();
    }

    private static ThreadLocal<LockObject> threadLocal = new ThreadLocal<LockObject>() {
        protected LockObject initialValue() {
            return new LockObject();
        }
    };

    public static void setLockKey(String key) {
        threadLocal.get().lockKey = key;
    }

    public static String getLockKey() {
        return threadLocal.get().lockKey;
    }

}

class LockObject {
    protected String lockKey;

    protected void reset() {
        lockKey = null;
    }
}